package cn.iocoder.yudao.module.wengfu.service.resultsdispatchroomdetails;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.module.wengfu.controller.admin.consignmentprocessingreport.vo.ConsignmentProcessingVO;
import com.anji.captcha.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.logging.Log;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

import cn.iocoder.yudao.module.wengfu.controller.admin.resultsdispatchroomdetails.vo.*;
import cn.iocoder.yudao.module.wengfu.dal.dataobject.resultsdispatchroomdetails.ResultsDispatchRoomDetailsDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.wengfu.dal.mysql.resultsdispatchroomdetails.ResultsDispatchRoomDetailsMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertList;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.diffList;
import static cn.iocoder.yudao.module.wengfu.enums.ErrorCodeConstants.*;

/**
 * 全分析结果统计＿调度室_明细 Service 实现类
 *
 * @author yzs
 */
@Service
@Validated
@Slf4j
public class ResultsDispatchRoomDetailsServiceImpl implements ResultsDispatchRoomDetailsService {

    private static final String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss.SSS";

    @Resource
    private ResultsDispatchRoomDetailsMapper resultsDispatchRoomDetailsMapper;

    @Override
    public String createResultsDispatchRoomDetails(ResultsDispatchRoomDetailsSaveReqVO createReqVO) {
        // 插入
        ResultsDispatchRoomDetailsDO resultsDispatchRoomDetails = BeanUtils.toBean(createReqVO, ResultsDispatchRoomDetailsDO.class);
        resultsDispatchRoomDetailsMapper.insert(resultsDispatchRoomDetails);

        // 返回
        return resultsDispatchRoomDetails.getRcid();
    }

    @Override
    public void updateResultsDispatchRoomDetails(ResultsDispatchRoomDetailsSaveReqVO updateReqVO) {
        // 校验存在
        validateResultsDispatchRoomDetailsExists(updateReqVO.getRcid());
        // 更新
        ResultsDispatchRoomDetailsDO updateObj = BeanUtils.toBean(updateReqVO, ResultsDispatchRoomDetailsDO.class);
        resultsDispatchRoomDetailsMapper.updateById(updateObj);
    }

    @Override
    public void deleteResultsDispatchRoomDetails(String id) {
        System.out.println("123456789");
        // 校验存在
        validateResultsDispatchRoomDetailsExists(id);
        // 删除
        resultsDispatchRoomDetailsMapper.deleteById(id);
    }

    @Override
        public void deleteResultsDispatchRoomDetailsListByIds(List<String> ids) {
        // 删除
        resultsDispatchRoomDetailsMapper.deleteByIds(ids);
        }


    private void validateResultsDispatchRoomDetailsExists(String id) {
        if (resultsDispatchRoomDetailsMapper.selectById(id) == null) {
            throw exception(RESULTS_DISPATCH_ROOM_DETAILS_NOT_EXISTS);
        }
    }

    @Override
    public ResultsDispatchRoomDetailsDO getResultsDispatchRoomDetails(String id) {
        return resultsDispatchRoomDetailsMapper.selectById(id);
    }

    @Override
    public PageResult<ResultsDispatchRoomDetailsDO> getResultsDispatchRoomDetailsPage(ResultsDispatchRoomDetailsPageReqVO pageReqVO) {
        return resultsDispatchRoomDetailsMapper.selectPage(pageReqVO);
    }

    @Override
    public void test() {
        System.out.println("45133213");
    }

    @Override
    public Map<String, BigDecimal> getConsignmentProcessingSum(ResultsDispatchRoomDetailsRespVO respVO) {
        // 1. 查询原始数据列表
        List<ResultsDispatchRoomDetailsDO> dataList = getOriginalDataList(respVO);

        // 2. 如果数据为空，返回默认值
        if (dataList == null || dataList.isEmpty()) {
            return createEmptyResultMap();
        }

        // 3. 提取各列数据
        List<BigDecimal> quantities = new ArrayList<>();
        List<BigDecimal> p2o5List = new ArrayList<>();
        List<BigDecimal> mgoList = new ArrayList<>();
        List<BigDecimal> r2o3List = new ArrayList<>(); // Fe2O3 + Al2O3
        List<BigDecimal> sio2List = new ArrayList<>();

        for (ResultsDispatchRoomDetailsDO data : dataList) {
            if(data!=null) {
                if (data.getQuantity() != null) quantities.add(data.getQuantity());
                if (data.getP2o5() != null) p2o5List.add(data.getP2o5());
                if (data.getMgo() != null) mgoList.add(data.getMgo());

                // 计算 R2O3 = Fe2O3 + Al2O3
                BigDecimal fe2o3 = data.getFe2o3() != null ? data.getFe2o3() : BigDecimal.ZERO;
                BigDecimal al2o3 = data.getAl2o3() != null ? data.getAl2o3() : BigDecimal.ZERO;
                r2o3List.add(fe2o3.add(al2o3));

                if (data.getSio2() != null) sio2List.add(data.getSio2());
            }
        }

        // 4. 计算 N23 (sum(quantity)) - 保留两位小数
        BigDecimal n23 = quantities.stream()
                .reduce(BigDecimal.ZERO, BigDecimal::add)
                .setScale(2, RoundingMode.HALF_UP);

        // 5. 如果总量为0，返回默认值
        if (n23.compareTo(BigDecimal.ZERO) == 0) {
            return createEmptyResultMap();
        }

        // 6. 计算四个加权平均值 - 都保留两位小数
        BigDecimal weightedP2O5 = calculateWeightedAverage(quantities, p2o5List, n23);
        BigDecimal weightedMgO = calculateWeightedAverage(quantities, mgoList, n23);
        BigDecimal weightedR2O3 = calculateWeightedAverage(quantities, r2o3List, n23);
        BigDecimal weightedSiO2 = calculateWeightedAverage(quantities, sio2List, n23);

        // 7. 返回结果
        Map<String, BigDecimal> result = new HashMap<>();
        result.put("total_quantity", n23);                    // N23
        result.put("p2o5", weightedP2O5);           // SUMPRODUCT(N,O)/N23
        result.put("mgo", weightedMgO);             // SUMPRODUCT(N,P)/N23
        result.put("r2o3", weightedR2O3);           // SUMPRODUCT(N,Q)/N23
        result.put("sio2", weightedSiO2);           // SUMPRODUCT(N,R)/N23

        return result;
    }

    /**
     * 查询原始数据列表
     */
    private List<ResultsDispatchRoomDetailsDO> getOriginalDataList(ResultsDispatchRoomDetailsRespVO respVO) {
        QueryWrapper<ResultsDispatchRoomDetailsDO> queryWrapper = new QueryWrapper<>();


        // 时间范围条件
        queryWrapper.ge("start_sampling_time", respVO.getStartSamplingTime());
        queryWrapper.le("end_sampling_time", respVO.getEndSamplingTime());


        // 如果需要动态参数，可以使用respVO中的值
        if (StringUtils.isNotEmpty(respVO.getMiningSupplier())) {
            queryWrapper.eq("mining_supplier", respVO.getMiningSupplier());
        }
        if (StringUtils.isNotEmpty(respVO.getMiningField())) {
            queryWrapper.like("mining_field", respVO.getMiningField());
        }
        if (StringUtils.isNotEmpty(respVO.getMiningUnit())) {
            queryWrapper.like("mining_unit", respVO.getMiningUnit());
        }
        if (StringUtils.isNotEmpty(respVO.getOreProperty())) {
            queryWrapper.like("ore_property", respVO.getOreProperty());
        }


        // 排序条件
        queryWrapper.orderByAsc("start_sampling_time");

        // 选择需要的字段
        queryWrapper.select("quantity", "P2O5", "MgO", "Fe2O3", "Al2O3", "SiO2");

        return resultsDispatchRoomDetailsMapper.selectList(queryWrapper);
    }

    /**
     * 计算加权平均值 (对应Excel的 SUMPRODUCT(N列, O列)/N23) - 保留两位小数
     */
    private BigDecimal calculateWeightedAverage(List<BigDecimal> nValues, List<BigDecimal> oValues, BigDecimal n23) {
        try {
            // 检查数据有效性
            if (nValues == null || oValues == null || nValues.size() != oValues.size() || nValues.isEmpty()) {
                return BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP);
            }

            // 计算 SUMPRODUCT: sum(n[i] * o[i])
            BigDecimal sumProduct = BigDecimal.ZERO;
            for (int i = 0; i < nValues.size(); i++) {
                BigDecimal nVal = nValues.get(i);
                BigDecimal oVal = oValues.get(i);
                if (nVal != null && oVal != null) {
                    sumProduct = sumProduct.add(nVal.multiply(oVal));
                }
            }

            // 除以 N23，保留2位小数，四舍五入
            return sumProduct.divide(n23, 2, RoundingMode.HALF_UP);

        } catch (Exception e) {
            // 如果出现任何错误，返回0 (对应Excel的ISERROR处理)
            return BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP);
        }
    }

    /**
     * 创建空结果Map - 所有值都保留两位小数
     */
    private Map<String, BigDecimal> createEmptyResultMap() {
        Map<String, BigDecimal> emptyMap = new HashMap<>();
        emptyMap.put("total_quantity", BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP));     // N23
        emptyMap.put("p2o5", BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP));      // SUMPRODUCT(N,O)/N23
        emptyMap.put("mgo", BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP));       // SUMPRODUCT(N,P)/N23
        emptyMap.put("r2o3", BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP));      // SUMPRODUCT(N,Q)/N23
        emptyMap.put("sio2", BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP));      // SUMPRODUCT(N,R)/N23
        return emptyMap;
    }





}
